package org.example.back.controller.Forum;

import org.example.back.entity.Forum.ForumMedia;
import org.example.back.service.Forum.ForumMediaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/forum/media")
public class ForumMediaController {

    @Autowired
    private ForumMediaService forumMediaService;

    @Value("${upload.path}")
    private String uploadPath;

    @PostMapping("/upload")
    public Map<String, Object> uploadMedia(@RequestParam("postId") Long postId,
                                       @RequestParam("type") String type,
                                       @RequestParam("file") MultipartFile file) throws IOException {
        Map<String, Object> result = new HashMap<>();
        if (file.isEmpty()) {
            result.put("success", false);
            result.put("message", "上传失败，文件为空");
            return result;
        }

        // 获取项目根目录
        String rootPath = System.getProperty("user.dir");
        String absoluteUploadPath = rootPath + File.separator + uploadPath;

        // 确保目录存在
        File uploadDir = new File(absoluteUploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 生成唯一文件名
        String filename = UUID.randomUUID() + "_" + StringUtils.cleanPath(file.getOriginalFilename());
        File dest = new File(absoluteUploadPath + File.separator + filename);

        System.out.println("文件保存路径：" + dest.getAbsolutePath());
        file.transferTo(dest);

        // 保存数据库记录
        ForumMedia media = new ForumMedia();
        media.setPostId(postId);
        media.setMediaType(type);
        media.setMediaUrl("/uploads/" + filename);  // 这里保存的是访问URL
        media.setUploadedAt(LocalDateTime.now());

        forumMediaService.addMedia(media);

        result.put("success", true);
        result.put("url", media.getMediaUrl());
        result.put("message", "上传成功");
        return result;
    }

    @GetMapping("/list/{postId}")
    public List<ForumMedia> getMediaListByPostId(@PathVariable("postId") Long postId) {
        // 查询该 postId 下的所有媒体记录
        return forumMediaService.getMediaByPostId(postId);
    }
}
